<template>
  <div>
    <searchBox @searchChange="searchChange" />
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-text
          class="mx-1"
          size="large"
        >Openid
        </el-text>
        <div>
          <el-input
            v-model="openid"
            placeholder="请输入openid查询"
            clearable
          />
        </div>

        <el-text
          class="mx-1"
          size="large"
        >行为</el-text>
        <div>
          <el-select
            v-model="flags"
            multiple
            collapse-tags
            style="width:200px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in burialsOption"
              :key="item.flag"
              :label="item.name"
              :value="item.flag"
            />
          </el-select>
        </div>
        <div>
          <el-button
            type="primary"
            icon="search"
            @click="getData"
          >查询</el-button>
          <el-button
            v-if="isShow"
            type="default"
            icon="download"
            @click="downloadCSV"
          >下载全部数据</el-button>
        </div>

      </div>
      <!-- 组件列表 -->

      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        border
        row-key="ID"
      >

        <el-table-column
          align="left"
          label="时间"
          prop="created_at"
          width="200"
        />
        <el-table-column
          align="left"
          label="行为"
          prop="event_string"
        />
      </el-table>

      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import searchBox from '../../components/search/searchBox.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { rpcGet } from '@/api/rpc'
import {
  getQmEventDetailList,
  getQmBurialList
} from '@/api/qmBurial'
const searchInfo = ref({})
const openid = ref()
const page = ref(1)
const total = ref(0)
const pageSize = ref(100)
const tableData = ref([])
const burials = ref([])
const burialsOption = ref({})
const flags = ref([])

const serverList = ref([])
const selectServer = ref('')

const isShow = ref(false)

const searchChange = function(date) {
  searchInfo.value = date
  if (openid.value) { getTableList() }
}
const getData = function() {
  getTableList()
}

const isPlatform = () => {
  const platform = localStorage.getItem('platform')
  if (platform == 0 || platform == '' || platform == null || platform == undefined) {
    ElMessage({
      type: 'error',
      message: '请先选择渠道'
    })
    return false
  }
  return true
}
const isOpenid = () => {
  if (!openid.value) {
    ElMessage({
      type: 'error',
      message: '输入openid'
    })
    return false
  }
  return true
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableList()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableList()
}

const getTableList = async() => {
  if (!isPlatform() || !isOpenid()) return
  const table = await getQmEventDetailList({ openid: openid.value, page: page.value, page_size: pageSize.value, flags: flags.value.join(','), ...searchInfo.value })
  	if (table.code === 0) {
    tableData.value = []
    if (table.data.event_detail) {
      table.data.event_detail.forEach(item => {
        const date = new Date(item.created_at)
        item.created_at = date.toLocaleString()
        item.event_string = getEventDesc(item)
        tableData.value.push(item)
      })
      total.value = table.data.total
    } else {
      total.value = 0
    }
  }

  if (total.value > 0 && flags.value.length == 1) {
    isShow.value = true
  } else {
    isShow.value = false
  }
}

const getEventDesc = function(item) {
  let text = burials.value[item.oper_type]
  text = text == undefined ? item.oper_type : text
  switch (item.oper_type) {
    case 'itemEvent':
      const content = JSON.parse(item.content)
      text += ' ' + content.name + ' ' + content.number
      break
    case 'schedule':
      const scheduleContent = JSON.parse(item.content)
      text += ' ' + scheduleContent.name + ' ' + (scheduleContent.status == 1 ? '进入' : (scheduleContent.status == 2 ? '通关' : '失败'))
      break
    default:
      text += ''
  }
  return text
}

// 查询
const getBurialsData = async() => {
  const table = await getQmBurialList({ page: 1, pageSize: 1000 })
  if (table.code === 0) {
    tableData.value = []
    burialsOption.value = table.data.list
    table.data.list.forEach(item => {
      burials.value[item.flag] = item.name
    })
    console.log(burials.value)
  }
}

const downloadCSV = async() => {
  if (!isPlatform() || !isOpenid()) return

  // 判断是否有数据 或者选择的行为是否为1
  if (total.value == 0) {
    ElMessage({
      type: 'error',
      message: '数据为空,无法下载'
    })
    return
  }

  if (flags.value.length != 1) {
    ElMessage({
      type: 'error',
      message: '下载只能选择一个行为'
    })
    return
  }

  // 创建CSV数据
  const csvData = [
    ['时间', '行为']
  ]
  const allData = []
  for (let i = 1; i <= Math.ceil(total.value / pageSize.value); i++) {
    const d = await getQmEventDetailList({ openid: openid.value, page: i, page_size: pageSize.value, flags: flags.value.join(','), ...searchInfo.value })
    d.data.event_detail.forEach(item => {
	  const date = new Date(item.created_at)
      csvData.push([date.toLocaleString(), getEventDesc(item)])
    })
  }

  // 将数据转换为CSV字符串
  let csvString = ''
  for (const row of csvData) {
    csvString += row.join(',') + '\n'
  }

  // 创建一个Blob对象，用于表示要下载的数据
  const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' })

  // 创建一个链接元素，用于触发下载
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', openid.value + '.csv') // 设置下载的文件名
  document.body.appendChild(link) // 将链接添加到文档中
  link.click() // 触发下载

  // 清理：移除链接元素，并释放blob URL
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}
getBurialsData()
</script>
